package com.zhixin.fans.ks.ui.charge;

import android.app.Activity;
import android.arch.lifecycle.Observer;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.zhixin.fans.ks.R;
import com.zhixin.fans.ks.api.CommonApi;
import com.zhixin.fans.ks.api.res.CoinOption;
import com.zhixin.fans.ks.api.res.OrderInfo;
import com.zhixin.fans.ks.api.res.UserInfo;
import com.zhixin.fans.ks.api.res.UserInfoRes;
import com.zhixin.fans.ks.api.res.WxPayInfo;
import com.zhixin.fans.ks.manager.UserInfoManager;
import com.zhixin.fans.ks.ui.base.BaseNeedLoginActivity;
import com.zhixin.fans.ks.ui.utils.PayUtil;

import org.eenie.common.managers.PayManager;
import org.eenie.common.subscribes.ProgressSubscriber;
import org.eenie.common.views.QMUIWindowInsetLinearLayout;
import org.eenie.common.views.TopBarLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;


public class ChargeCoinActivity extends BaseNeedLoginActivity implements Observer<UserInfo> {

    public static final String ROUTE_PATH = "/charge/charge_coin";

    @BindView(R.id.top_bar)
    TopBarLayout mTopBar;
    @BindView(R.id.img_user_header)
    ImageView mImgUserHeader;
    @BindView(R.id.rv_coin_option)
    RecyclerView mRvCoinOption;
    @BindView(R.id.fragment_container)
    QMUIWindowInsetLinearLayout mFragmentContainer;


    CoinChargeAdapter mCoinChargeAdapter;

    List<CoinOption> mCoinOptions = new ArrayList<>();

    //    CoupleApi mCoupleApi;
    @BindView(R.id.tv_user_name)
    TextView mTvUserName;
    @BindView(R.id.tv_user_id)
    TextView mTvUserId;
    @BindView(R.id.tv_fb_count)
    TextView mTvFbCount;
    @BindView(R.id.btn_buy_fb)
    QMUIRoundButton mBtnBuyFb;
    @BindView(R.id.tv_pay_money)
    TextView mTvPayMoney;
    @BindView(R.id.btn_submit)
    Button mBtnSubmit;


    UserInfoManager mUserInfoManager;

    CoinOption mCoinOption;

    PayManager mPayManager;

    CommonApi mCommonApi;


    @Override
    public int initContentView() {
        return R.layout.activity_charge_coin;
    }

    @Override
    public void initInjector() {
        mCommonApi = getApplicationComponent().getApiManager().create(CommonApi.class);
        mUserInfoManager = getCoupleAppComponent().getUserInfoManager();
        mPayManager = getApplicationComponent().getPayManager();
        mPayManager.observe(this, new Observer<BaseResp>() {
            @Override
            public void onChanged(BaseResp baseResp) {
                if (baseResp.errCode == 0) {
                    fetchUserInfo();
                }
            }
        });
    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        mRvCoinOption.setLayoutManager(new GridLayoutManager(mContext, 2));
        mRvCoinOption.setAdapter(mCoinChargeAdapter = new CoinChargeAdapter(mCoinOptions) {
            @Override
            public void onItemSelected(CoinOption coinOption) {
                mCoinOption = coinOption;
                mTvPayMoney.setText(String.format("支付金额：￥%s", coinOption.getP_money()));
            }
        });

        mTopBar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mUserInfoManager.observe(this, this);
        mUserInfoManager.update();
        fetchFbList();

    }


    @OnClick(R.id.btn_buy_fb)
    public void buyFb() {
    }

    @OnClick(R.id.btn_submit)
    public void submit() {
        if (mCoinOption == null) {
            ToastUtils.showShort("请选择要充值的项目");
        } else {
            submitPayOrder(mCoinOption.getP_id());
        }
    }

    @Override
    public void onChanged(UserInfo userInfo) {
        if (userInfo != null && userInfo.getU_id() > 0) {
            Glide.with(mContext).asBitmap().load(userInfo.getU_headPicture()).into(mImgUserHeader);
            mTvUserName.setText(userInfo.getU_nickName());
            mTvUserId.setText(String.format("ID：%s", userInfo.getU_id()));
            mTvFbCount.setText(String.format("粉币：%s", userInfo.getU_usermoney()));
        }

    }


    private void fetchFbList() {
        mCommonApi.fetchCoinList()
                .subscribe(new ProgressSubscriber<List<CoinOption>>() {
                    @Override
                    public void onNext(List<CoinOption> coinOptions) {
                        mCoinOptions.clear();
                        mCoinOptions.addAll(coinOptions);
                        mCoinChargeAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFinish() {

                    }
                });
    }


    private void submitPayOrder(int goodId) {
        mCommonApi.submitPayOrder("POINT", goodId)
                .flatMap(new Function<OrderInfo, ObservableSource<WxPayInfo>>() {
                    @Override
                    public ObservableSource<WxPayInfo> apply(OrderInfo orderInfo) throws Exception {
                        return mCommonApi.fetchPayInfo(orderInfo.getOrderId());
                    }
                })
                .subscribe(new ProgressSubscriber<WxPayInfo>(mContext) {
                    @Override
                    public void onNext(WxPayInfo payInfo) {
                        PayUtil.payWx(mContext, payInfo);
                    }

                    @Override
                    public void onFinish() {

                    }
                });
    }

    private void fetchUserInfo() {
        mCommonApi.fetchUserInfo("")
                .subscribe(new ProgressSubscriber<UserInfoRes>(mContext) {
                    @Override
                    public void onNext(UserInfoRes userInfoDetail) {
                        mUserInfoManager.setValue(userInfoDetail.getUserInfo());
                        setResult(Activity.RESULT_OK);
                        ToastUtils.showShort("充值成功");
                        finish();
                    }

                    @Override
                    public void onFinish() {


                    }
                });
    }


}
